// Written by Dale J Williams.
// Licensed under MPL 1.1 unless otherwise specified. 
// http://www.mozilla.org/MPL/MPL-1.1.html

package engineDJW.map {
	
	import engineDJW.effects.Effect;
	import engineDJW.entities.Entity;
	import flash.display.Sprite;
	import flash.display.DisplayObjectContainer;
	
	/**
	 * ...
	 * @author Dale J Williams
	 */
	public class GameMap extends Sprite {
		
		private var _entities	:Vector.<Entity>;
		private var _effects	:Vector.<Effect>;
		
		public function GameMap($super:*) {
			init();
		}
		
		private function init():void {
			_entities = new Vector.<Entity>();
			_effects = new Vector.<Effect>();
			mouseEnabled = mouseChildren = false;
		}
		
		public function removeAllEntities():void {
			while (_entities.length > 0)
				removeEntity(_entities.pop());
		}
		
		public function removeAllEffects():void {
			while (_effects.length > 0)
				removeEntity(_effects.pop());
		}
		
		// ENTITY MANAGEMENT
		public function addEntity($entity:Entity):Entity { 	return _addToMap($entity, _entities, this); }		
		public function getEntity($name:String):Entity { return _getMapObject($name, _entities); }		
		public function removeEntity($entity:Entity, $fromParent:Boolean=true):Entity { return _removeFromMap($entity, _entities, $fromParent); }
		
		// EFFECT MANAGEMENT
		public function addEffect($effect:Effect, $container:DisplayObjectContainer=null):Entity { 	return _addToMap($effect, _effects); }		
		public function getEffect($name:String):Entity { return _getMapObject($name, _effects); }		
		public function removeEffect($effect:Effect, $fromParent:Boolean=true):Entity { return _removeFromMap($effect, _effects, $fromParent); }
		
		// ADD / REMOVE FUNCTIONS
		private function _addToMap($entity:Entity, $collection:Object, $container:DisplayObjectContainer = null):Entity {
			if (!$container) $container = this;
			$collection.push($entity);
			$container.addChild($entity);
			$entity.map = this;
			return $entity;
		}
		
		public function _getMapObject($name:String, $collection:Object):Entity {
			var i:int = $collection.length;
			while (i--)
				if ($collection[i].name == $name)
					return $collection[i];
			return null;
		}
		
		private function _removeFromMap($entity:Entity, $collection:Object, $fromParent:Boolean=true):Entity {
			var i:int = $collection.length;
			while (i--) {
				if ($collection[i] != $entity) continue;
				if ($fromParent && $entity.parent) $entity.parent.removeChild($entity);
				$collection.splice(i, 1);
				$entity.map = null;
				return $entity;
			}
			return null;
		}
		
		public function update():void {
			for each(var entity:Entity in _entities)
				entity.update();
			for each(var effect:Effect in _effects)
				effect.update();
		}
		
		public function get entities():Vector.<Entity> { return _entities; }
		
		public function get effects():Vector.<Effect> { return _effects; }
		
	}

}